import React, { Component } from 'react'
import ReactDom from 'react-dom'
import { Router, Route, Link, IndexLink, hashHistory, IndexRoute } from 'react-router'
import { Navbar, Nav, NavItem, NavDropdown, MenuItem, Table, Grid, Button, ButtonGroup } from 'react-bootstrap'


import RecommendationList from './RecommendationList'
import BookList from './BookList'
import BookDetails from './BookDetails'
import ReadBook, { SinglePage, DoublePage } from './ReadBook'
import * as Actions from '../actions'
import async from 'Async'

require("./Books.css")


export default class Books extends Component {
    constructor(props) {
        super(props)
        this.state = { navTrack: {}, keyword: "" }
    }
    _resetNavTrack(recommendationId) {
        console.log("recommendationId: ", recommendationId)
        let {navTrack} = this.state
        let last = navTrack.current || ""
        let current = recommendationId
        this.setState(Object.assign({}, this.state, {}))
    }
    _test(id) {
        console.log("test id: ", id)
    }

    componentDidMount() {
        let {keyword} = this.props.params
        this.setState({ keyword })

    }
    onChangeSearchInput(keyword) {
        this.setState({ keyword })
        window.location = `#/search/${keyword}`
    }
    render() {
        let {recommendationId} = this.props.params

        let {navTrack} = this.state
        // <div style={{ fontSize: "14px", color: "#ffffff", margin: "18px 5px", float: "right" }}>注销</div>
        // <div style={{ fontSize: "14px", color: "#ffffff", margin: "18px 5px", float: "right" }}>登录</div>
        // <div style={{ width: "150px", height: "25px", margin: "15px 5px", backgroundColor: "#ffffff", float: "right" }}>
        //     <i className="fa fa-lock" style={{ width: "20%", textAlign: "center" }}></i>
        //     <input type="password" style={{ height: "100%", width: "80%", border: 0, outline: "none" }} />
        // </div>
        // <div style={{ width: "150px", height: "25px", margin: "15px 0px", backgroundColor: "#ffffff", float: "right" }}>
        //     <i className="fa fa-user" style={{ width: "20%", textAlign: "center" }}></i>
        //     <input type="text" style={{ height: "100%", width: "80%", border: 0, outline: "none" }} />
        // </div>


        return <div style={{ minWidth: "1200px" }}>
            <div style={{ height: "90px", backgroundColor: "#3A7FB5" }}>
                <a href="./">
                    <div style={{ width: "1200px", height: "90px", margin: "auto", paddingTop: "17px" }}>
                        <div className="books-logo" style={{ float: "left" }}></div>
                        <div style={{ fontSize: "18px", fontFamily: "微软雅黑", margin: "18px 5px", color: "#ecf1f5", float: "left" }}>重庆市巴南区图书馆</div>
                        <div style={{ fontSize: "12px", fontFamily: "微软雅黑", margin: "27px 0px", color: "#ecf1f5", float: "left" }}>bntsg.cn</div>
                    </div>
                </a>
            </div >
            <div style={{ width: "1200px", margin: "45px auto" }}>
                <div style={{ width: "899px", float: "left" }}>
                    {this.props.children}
                </div>
                <div style={{ width: "291px", float: "left", marginLeft: "9px" }}>
                    <div style={{ height: "67px", backgroundColor: "#F7F7F7", border: "#D5D5D5 1px solid" }}>
                        <div style={{ height: "37px", margin: "13px 13px" }}>
                            <input type="text" style={{ width: "197px", height: "100%", float: "left", outline: "none" }} onChange={ev => { this.onChangeSearchInput(ev.target.value) } } value={this.state.keyword} />
                            <div onClick={() => { this.search() } } style={{ width: "65px", height: "100%", lineHeight: "37px", backgroundColor: "#3A7FB5", float: "left", fontSize: "14px", color: "#ffffff", textAlign: "center" }}>检索</div>
                        </div>
                    </div>
                    <RightNav currentCategoryId={recommendationId} />
                    <NewRecBooks />
                    <div className="books-to-top" onClick={() => {
                        window.scrollTo(0, 0)
                    } }>
                        <i className="fa fa-angle-up fa-2x"></i>
                        <span>TOP</span>
                    </div>

                </div>
            </div>
            <div style={{ clear: "both" }}></div>
            <Footer />


        </div >
    }
}




class TopNav extends Component {
    render() {
        console.log("TopNav: ")

        return <div></div>
    }
}
class RightNav extends Component {
    constructor(props) {
        super(props)
        this.state = { navNodeTrack: {}, categoryList: [] }
    }
    componentDidMount() {
        let categoryList = []
        Actions.getAllCategories((categoryList) => {
            console.log("categorylist: ", categoryList)
            let {currentCategoryId} = this.props
            categoryList.forEach(category => {
                category.children.forEach(subCategory => {
                    if (subCategory.categoryId == currentCategoryId) {
                        subCategory.active = true
                        category.expand = true
                    }
                })
            })
            this.setState({ categoryList })
        })
    }
    onClickCategory(category) {
        category.expand = !category.expand
        this.forceUpdate()
    }
    onClickSubCategory(subCategory) {
        window.location = `#/booklist/${subCategory.categoryId}`
    }
    render() {
        return <div>
            <ul style={{ listStyleType: "none", marginTop: "10px", backgroundColor: "#FFFFFF", border: "#D5D5D5 1px solid", paddingLeft: 0 }}>
                {this.state.categoryList.map((category, i) =>
                    <li onClick={() => this.onClickCategory(category)} key={category.categoryId} style={{ borderTop: i === 0 ? 0 : "#D5D5D5 1px solid" }}>
                        <span style={{ height: "37px", lineHeight: "37px", fontSize: 16, fontFamily: "微软雅黑", color: "#3a7fb5" }}><i className="fa fa-angle-right">&nbsp;</i>{category.title}</span>
                        {category.expand ?
                            <ul style={{ listStyleType: "none" }} >
                                {category.children.map(subCategory => <li onClick={() => this.onClickSubCategory(subCategory)} key={subCategory.categoryId}
                                    style={{ fontWeight: subCategory.active ? "bold" : "normal" }}>
                                    {subCategory.title}
                                </li>)}
                            </ul>
                            : null}
                    </li>)}
            </ul>
        </div>
        // console.log("RightNav: ", this.props.resetNavTrack)
        // let {navTrack, resetNavTrack} = this.props
        // let rightNavList = recommendations.map((item, index) => {
        //     if (item.id === navTrack.current) {
        //         return <div key={index} className="books-right-nav books-nav-active">
        //             <Link className="link" to={`/booklist/${item.id}`} onClick={() => resetNavTrack(item.id)}>-&nbsp;{item.title}</Link>
        //         </div>
        //     } else {
        //         return <div key={index} className="books-right-nav">
        //             <Link className="link" to={`/booklist/${item.id}`} onClick={() => resetNavTrack(item.id)}>-&nbsp;{item.title}</Link>
        //         </div>
        //     }
        // })
        // return 0 > 1 ?
        //     <div style={{ marginTop: "10px", backgroundColor: "#FFFFFF", border: "#D5D5D5 1px solid", borderBottom: "none" }}>
        //         {rightNavList}
        //     </div>
        //     :
        //     <div>1212</div>
    }
}
class NewRecBooks extends Component {
    constructor() {
        super()
        this.state = { recommendation: null, books: null }
    }
    componentDidMount() {
        Actions.getRecommendationList().then(recommendationList => {
            var recommendation = {}
            recommendationList.map((item, i) => {
                if (item.sortValue === 50) {
                    recommendation = item
                }
            })
            this.setState({ recommendation })
            let books_ = []
            async.series(recommendation.books.map(bookId => (callback) => {
                Actions.getBook(bookId).then(book => {
                    books_.push(book)
                    callback(null)
                })
            }), (err) => {
                this.setState({ books: books_ })
            })
        })
    }
    render() {
        console.log("NewRecBooks: ")
        if (!this.state.recommendation || !this.state.books) {
            return null
        }
        let reclist = this.state.books.map((item, index) => {
            if (index <= 2) {
                return <div key={index} className="books-right-rec ">
                    <div className="top-three">{index + 1}</div>
                    <Link className="link" to={`/readbook/${item.bookId}`}>{item.name}</Link>
                </div>
            } else {
                return <div key={index} className="books-right-rec ">
                    <div className="other">{index + 1}</div>
                    <Link className="link books-only-one" to={`/readbook/${item.bookId}`}>{item.name}</Link>
                </div>
            }
        })
        return <div style={{ marginTop: "10px", border: "#D5D5D5 1px solid", borderTop: "#4669E1 2px solid" }}>
            <div style={{ height: "50px", borderBottom: "#D5D5D5 1px solid", backgroundColor: "#F5F5F5" }}>
                <div style={{ marginLeft: "20px", lineHeight: "50px", fontSize: "18px", fontFamily: "微软雅黑", color: "#515151", float: "left" }}>{this.state.recommendation.title}</div>
            </div>
            <div style={{ padding: "5px 0px", background: "#FFFFFF" }}>
                {reclist}
            </div>
        </div>

    }
}
class ClickRanklist extends Component {
    render() {
        console.log("ClickRanklist: ")
        let ranklist = books.map((item, index) => {
            if (index === 0) {
                return <div key={index} className="books-ranklist-book ">
                    <div className="top-one">{index + 1}</div>
                    <Link className="link books-only-one" to={`/bookdetails/${item.id}`}>{item.title}</Link>
                    <span>{item.tickets}</span>
                </div>
            } else if (index === 1) {
                return <div key={index} className="books-ranklist-book ">
                    <div className="top-two">{index + 1}</div>
                    <Link className="link books-only-one" to={`/bookdetails/${item.id}`}>{item.title}</Link>
                    <span>{item.tickets}</span>
                </div>
            } else if (index === 2) {
                return <div key={index} className="books-ranklist-book ">
                    <div className="top-three">{index + 1}</div>
                    <Link className="link books-only-one" to={`/bookdetails/${item.id}`}>{item.title}</Link>
                    <span>{item.tickets}</span>
                </div>
            } else {
                return <div key={index} className="books-ranklist-book ">
                    <div className="other">{index + 1}</div>
                    <Link className="link books-only-one" to={`/bookdetails/${item.id}`}>{item.title}</Link>
                    <span>{item.tickets}</span>
                </div>
            }

        })
        return books[0] ?
            <div style={{ marginTop: "10px", border: "#D5D5D5 1px solid", borderTop: "#4669E1 2px solid" }}>
                <div style={{ height: "50px", borderBottom: "#D5D5D5 1px solid", backgroundColor: "#F5F5F5" }}>
                    <div style={{ marginLeft: "20px", lineHeight: "50px", fontSize: "18px", fontFamily: "微软雅黑", color: "#515151", float: "left" }}>点击排行</div>
                    <div style={{ marginTop: "20px", marginLeft: "150px", float: "left" }}><a href="#">更多<i className="fa fa-angle-double-right"></i></a></div>
                </div>
                <div style={{ padding: "5px 0px", background: "#FFFFFF" }}>
                    {ranklist}
                </div>
            </div>
            :
            <div></div>
    }
}

class Test extends Component {
    render() {
        console.log("test fuc: ", this.props.test)
        // this.props.test("test1234")
        let test = this.props.test
        return <div onClick={() => test("test1234")}>
            点我执行！
        </div>
    }
}

class Footer extends Component {
    render() {
        return <div style={{ marginTop: "50px" }}>
            <div style={{ height: "10px", backgroundColor: "#5489b3" }}></div>
            <div style={{ height: "300px", backgroundColor: "#2e6590", paddingTop: "35px" }}>
                <div style={{ width: "1200px", margin: "auto" }}>
                    <div className="books-footer-link">
                        <div>相关网站</div>
                        <a href="#">国家图书馆</a>
                        <a href="#">重庆图书馆</a>
                        <a href="#">重庆群众艺术馆</a>
                        <a href="#">重庆三峡博物馆</a>
                        <a href="#">巴南区图书馆</a>
                        <a href="#">巴南区文化馆</a>
                    </div>
                    <div className="books-footer-link" style={{ marginLeft: "50px" }}>
                        <div>常用链接</div>
                        <a href="#">重庆市人民政府</a>
                        <a href="#">重庆市巴南区人民政府</a>
                        <a href="#">重庆市文化委员会</a>
                        <a href="#">重庆市巴南区文化委员会</a>

                    </div>
                    <div className="books-footer-link" style={{ marginLeft: "50px" }}>
                        <div>联系方式</div>
                        <a className="unhover">地址：重庆市巴南区鱼洞街道下河路17号</a>
                        <a className="unhover">邮政编码:400037</a>
                        <a className="unhover">咨询电话:023-66223062</a>
                        <a className="unhover">邮箱:bntsg@163.com</a>

                    </div>
                    <div style={{ marginLeft: "130px", float: "left" }}>
                        <div>
                            <a href="#"><i className="fa fa-weibo fa-3x" style={{ color: "#FFFFFF" }}></i></a>
                            <a href="#" style={{ color: "#FFFFFF", margin: "0px 30px" }}><i className="fa fa-weixin fa-3x"></i></a>
                            <a href="#"><i className="fa fa-tencent-weibo fa-3x" style={{ color: "#FFFFFF" }}></i></a>
                        </div>
                        <div>
                            <a href="#" className="books-foot-enterprise"></a>
                        </div>

                    </div>
                    <div style={{ marginLeft: "35px", float: "left" }}>
                        <img src={'/dist/images/phone.png'} />
                    </div>
                    <div style={{ clear: "both" }}></div>
                </div>
                <div style={{ width: "1200px", margin: "auto", marginTop: "30px" }}>
                    <div className="books-foot-copyright" style={{ textAlign: "center" }}>Copyright © 2012-2016 巴南区图书馆版权所有 渝ICP备07006992号</div>
                    <div style={{ textAlign: "center" }}><a className="books-foot-copyright" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=50011302000147">渝公网安备 50011302000147号</a></div>
                </div>
            </div>
        </div >
    }
}

class LeftFastPath extends Component {
    render() {
        return <div style={{ position: "absolute", top: "225px" }}>
            <div className="books-left-fast">
                <i className="fa fa-phone fa-3x"></i>
                <span>热线</span>
            </div>
            <div className="books-left-fast">
                <i className="fa fa-qq fa-3x"></i>
                <span>QQ</span>
            </div>
            <div className="books-left-fast">
                <i className="fa fa-mobile fa-3x"></i>
                <span>手机APP</span>
            </div>
        </div>
    }
}

const getCategoryList = (categoryId) => {
    return fetch("/bookService/getCategoryListByParent", {
        method: 'POST', headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }, body: JSON.stringify({ parentId: categoryId })
    })
        .then(res => res.json())
}

const getAllSubCateList = (categoryList) => {
    let prom
    categoryList.map((category, i) => {
        getCategoryList(category.categoryId).then(function (res) {
            console.log("res: ", res)
            categoryList[i] = Object.assign({}, categoryList[i], { list: res })
            this.setState(Object.assign({}, this.state, ))
        }.bind(this), (reason) => {
            console.log("getCategoryList list err, index=" + i, reason)
            throw reason
        })
    })
}


const recommendations = [
    { id: '001', title: '小编推荐' },
    { id: '002', title: '都市言情' },
    { id: '003', title: '国学经典' },
    { id: '004', title: '社会百科' },
    { id: '005', title: '小编推荐' },
    { id: '006', title: '都市言情' },
    { id: '007', title: '国学经典' },
    { id: '008', title: '社会百科' }
]

const books = [
    { id: '001', title: "小王子", tickets: 221532 },
    { id: '002', title: "麦田里的守望者", tickets: 221032 },
    { id: '003', title: "追风筝的人", tickets: 220532 },
    { id: '004', title: "第七天", tickets: 201452 },
    { id: '005', title: "别相信任何人", tickets: 184552 },
    { id: '006', title: "偷影子的人", tickets: 142581 },
    { id: '007', title: "活着", tickets: 124568 },
    { id: '008', title: "世界上的另一个你", tickets: 121454 },
]


// 5B9AEA
// <Route path="/subcate/:categoryId" component={SubCategoryPage} />
// <Route path="/read/:id" component={ReadPage} />
ReactDom.render((
    <Router history={hashHistory}>
        <Route path="/" component={Books}>
            <IndexRoute component={RecommendationList} />
            <Route path="/booklist/:recommendationId" component={BookList} />
            <Route path="/bookdetails/:bookId" component={BookDetails} />
            <Route path="/search/:keyword" component={BookList} />
        </Route>
        <Route path="/readbook/:bookId" component={ReadBook}>
        </Route>
    </Router>
), document.querySelector("#web"))